package com.example.demo.entity;

import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.ToString;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import jakarta.persistence.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "user")
@EqualsAndHashCode(exclude = "bookkeepingRecords")
@ToString(exclude = "bookkeepingRecords")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "account", nullable = false, unique = true, length = 11)
    private String account;

    @Column(name = "username", length = 50)
    private String username;

    @Column(name = "password", length = 100) // 数据库中存储的是加密后的密码
    private String password; // 在Controller中返回给前端时，通常会将其设为null

    @Lob // 表示这是一个大对象字段
    @Column(name = "avatar", columnDefinition = "LONGTEXT") // 指定数据库类型为 LONGTEXT
    private String avatar; // 存储头像的 Base64 字符串或 URL

    @CreationTimestamp
    @Column(name = "add_time", updatable = false)
    private LocalDateTime addTime;

    @UpdateTimestamp
    @Column(name = "update_time")
    private LocalDateTime updateTime;

    @Column(name = "book_count")
    private Integer bookCount = 0;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    @JsonManagedReference // 添加此注解，表示这是关系的前端（父端），会被正常序列化
    private List<Bookkeeping> bookkeepingRecords = new ArrayList<>();
}
